package com.gxuwz.attend.dao.admin;

import com.gxuwz.attend.entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
@Repository

public class DepartmentDao {
    @Autowired

    private JdbcTemplate jdbcTemplate;


    public List<Department> getAllDepartments(int size, int offset) {
        String sql = "SELECT * FROM sys_department LIMIT ? OFFSET ?";
        return jdbcTemplate.query(sql, new Object[]{size, offset}, (rs, rowNum) -> {
            Department department = new Department();
            department.setDepID(rs.getString("depID"));
            department.setDepName(rs.getString("depName"));
            return department;

        });
    }

    public void addDepartment(Department department) {
        String sql = "INSERT INTO sys_department(depID, depName) VALUES(?, ?)";
        jdbcTemplate.update(sql, department.getDepID(), department.getDepName());
    }

    public void deleteDepartment(String depID) {
        String sql = "DELETE FROM sys_department WHERE depID=?";
        int rs = jdbcTemplate.update(sql, depID);
    }

    public void updateDepartment(Department department) {
        String sql = "UPDATE sys_department SET depName=?, depID=? WHERE depID=?";
        int rs = jdbcTemplate.update(sql, department.getDepName(), department.getDepID(), department.getId());
    }


    public List<Department> findDepartments(String depID,String depName,  int size, int offset) {
        // 构建基本的 SQL 查询
        StringBuilder sql = new StringBuilder("SELECT * FROM sys_department WHERE 1=1");
        List<Object> params = new ArrayList<>();

        // 根据部门ID模糊查询
        if (depID != null && !depID.isEmpty()) {
            sql.append(" AND depID LIKE ?");
            params.add("%" + depID + "%");
        }


        // 根据部门名称模糊查询
        if (depName != null && !depName.isEmpty()) {
            sql.append(" AND depName LIKE ?");
            params.add("%" + depName + "%");
        }


        // 添加分页限制
        sql.append(" LIMIT ? OFFSET ?");
        params.add(size);
        params.add(offset);

        // 执行查询并返回结果
        return jdbcTemplate.query(sql.toString(), params.toArray(), (rs, rowNum) -> {
            Department department = new Department();
            department.setDepID(rs.getString("depID"));
            department.setDepName(rs.getString("depName"));
            return department;
        });
    }


}
